package com.ht.shop.filters;




import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
public class MyLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //这个对一些地址进行登录过滤,比如需要登录才能访问的进行未登录的拦截, 有些不允许在登录状态下访问的进行登录拦截
        String uri = ((HttpServletRequest) servletRequest).getRequestURI();
        if (uri.contains("login.jsp")) {
            //如果在登录的情况下访问登录页面,我们将拦截到首页
            if (((HttpServletRequest) servletRequest).getSession().getAttribute("loginUser") != null) {
                //登录了 拦截
                ((HttpServletResponse) servletResponse).sendRedirect("/index.jsp");
                return;
            }

        } else if (uri.contains("/cart")||uri.contains("/order")) {//所有和购物车相关的操作都必须要登录
            if (((HttpServletRequest) servletRequest).getSession().getAttribute("loginUser") == null) {
                //没有登录.跳转到登录的页面
                ((HttpServletResponse) servletResponse).sendRedirect("/login.jsp");
                return;
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }
}
